package com.alibaba.cirtus.ots.application.adapter.ability.facade.service.sap;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.cirtus.ots.application.adapter.ability.utils.RequestUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.constant.SaleOrderConstants;
import com.alibaba.citrus.ots.common.util.PriceConvertUnit;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcots.model.dto.BaselineQueryChannelByPageRequest;
import com.epoch.app.bcots.model.dto.BaselineQueryScItemByPageRequest;
import com.epoch.app.bcots.platform_enhance.SaleOrderTag;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf014Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf014SDO;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif014.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif014.service.MnSapIf014Service;
import com.epoch.app.otsb2btradecenter.model.dto.TradeMessageSDO;
import com.epoch.app.otsb2btradecenter.sdo.OrderSDO;
import com.epoch.app.otsforecastsales.model.dto.ActivitySDO;
import com.epoch.app.otspricecenter.model.enums.ActivityTypeEnum;
import com.epoch.app.otsunifiedinventory.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.otsunifiedinventory.model.dto.QueryCargoZoneByIdResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/9/28 21:21
 */
@Component
public class MnSapIf014ServiceImpl implements MnSapIf014Service {

    @Autowired
    private BaseDataService baseDataService;

    private Log log = Log.getLogger(MnSapIf014ServiceImpl.class);

    @ProcessInvoker(remark = "MnSapIf014Service")
    @Override
    public Object doHandler(DoHandlerRequest doHandlerRequest) {
        log.info("DoHandlerRequest doHandlerRequest:" + JSONObject.toJSONString(doHandlerRequest));
        if (Objects.isNull(doHandlerRequest) || Objects.isNull(doHandlerRequest.getMessage())) {
            log.error("参数为空，直接返回！入参={}", doHandlerRequest);
            return false;
        }

        log.info("message:  " + doHandlerRequest.getMessage());
        TradeMessageSDO tradeMessageSDO = JSON.parseObject(doHandlerRequest.getMessage(), TradeMessageSDO.class);
        OrderSDO orderSDO = tradeMessageSDO.getOrderSDO();
        if (Objects.isNull(orderSDO)) {
            log.error("orderSDO为空，orderSDO = {}", orderSDO);
            return false;
        }
        if (CollectionUtils.isEmpty(orderSDO.getOrderLineSDOS())) {
            log.error("orderSDO.getOrderLineSDOS 为空，orderSDO = {}", orderSDO);
            return false;
        }
        if ("ZRE3".equals(orderSDO.getOrderType())) {
            return true;
        }

        MnSapIf014Request request = new MnSapIf014Request();
        request.setMessageHeader(RequestUtils.generateMessageHeader("MnSapIf014", "ECC"));

        List<MnSapIf014SDO> mnSapIf014DetailList = orderSDO.getOrderLineSDOS().stream().map(orderLineSDO -> {
            MnSapIf014SDO sdo = new MnSapIf014SDO();

//            if ("ZFD3".equals(orderSDO.getOrderType())) {
//
//            }
            //todo 赠品和特价活动的信息未传值 底嘉麟
            sdo.setGiftFlag("X");
            Map<String,String> features = orderLineSDO.getFeatures();
            List<ActivitySDO> activitySDOS = new ArrayList<>();
            if (Objects.nonNull(orderLineSDO.getFeatures()) && Objects.nonNull(features.get("activityDteails"))){
                activitySDOS = JSONObject.parseArray(features.get("activityDteails"), ActivitySDO.class);
            }
            if (MapUtils.isNotEmpty(features) && features.get("giftFlag") != null) {
                sdo.setGiftFlag(null);
            }

            //进行活动标识的拦截
            List<ActivitySDO> collect = activitySDOS.stream().filter(ActivitySDO::getIsSelect).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                collect.stream().forEach(activitySDO -> {
                    if (ActivityTypeEnum.SPECIAL_OFFER_PRICE.getValue().equals(activitySDO.getActivityType())){
                        sdo.setSpecialActivityId(activitySDO.getActivityCode());
                        sdo.setSpecialPromotionId(activitySDO.getActivityTermid());
                        if (activitySDO.getSpecialOfferPrice() != null) {
                            sdo.setActivityPrice(String.valueOf(activitySDO.getSpecialOfferPrice()/100));
                        }
//                    if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
//                        sdo.setManualPromotionId(orderLineSDO.getFeatures().get("activityNumber"));
//                    }
//                    sdo.setGiftFlag(null);
                    }
                    if (ActivityTypeEnum.TAKE_GIFT.getValue().equals(activitySDO.getActivityType())){
                        sdo.setGiftActivityId(activitySDO.getActivityCode());
                        sdo.setGiftPromotionId(activitySDO.getActivityTermid());
//                    if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
//                        sdo.setManualPromotionId(orderLineSDO.getFeatures().get("activityNumber"));
//                    }
                    }
                    if (ActivityTypeEnum.BUY_GIFT.getValue().equals(activitySDO.getActivityType())){
                        sdo.setGiftActivityId(activitySDO.getActivityCode());
                        sdo.setGiftPromotionId(activitySDO.getActivityTermid());
//                    if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
//                        sdo.setManualPromotionId(orderLineSDO.getFeatures().get("activityNumber"));
//                    }
                    }
                    if (ActivityTypeEnum.REPLENISHMENT.getValue().equals(activitySDO.getActivityType())){
                        sdo.setActivityId(activitySDO.getActivityCode());
                        sdo.setManualPromotionId(activitySDO.getActivityTermid());
//                    sdo.setGiftFlag(null);
                    }
                });
            }

            sdo.setTradeOrderId(orderSDO.getId());
            sdo.setOrderType(orderSDO.getOrderType());

            //平台销售组织->sap
            BaselineGetOrganizationByIdsRequest organizationByIdsRequest = new BaselineGetOrganizationByIdsRequest();
            List<String> saleIds = new ArrayList<>();
            saleIds.add(orderSDO.getOrganizationCode());
            saleIds.add(orderSDO.getDepartmentCode());
            saleIds.add(orderSDO.getSaleChannelCode());
            organizationByIdsRequest.setIds(saleIds);
            Map saleMap = (Map) baseDataService.baselineGetOrganizationByIds(organizationByIdsRequest);
            JSONArray result = JSONObject.parseObject(JSONObject.toJSONString(saleMap)).getJSONArray("result");
            if (CollectionUtils.isNotEmpty(result)) {
                for (int i = 0; i < result.size(); i++) {
                    JSONObject organizationSDO = result.getJSONObject(i).getJSONObject("organizationSDO");
                    String orgId = organizationSDO.getString("id");
                    if (orderSDO.getOrganizationCode().equals(orgId)) {
                        sdo.setSaleOrganizationCode(organizationSDO.getString("outCode"));
                    }
                    if (orderSDO.getDepartmentCode().equals(orgId)) {
                        sdo.setSaleGroup(organizationSDO.getString("outCode"));
                    }
                    if (orderSDO.getSaleChannelCode().equals(orgId)) {
                        sdo.setSaleDepartmentCode(organizationSDO.getString("outCode"));
                    }
                }
            }

            //平台发货仓->sap工厂和库存地点
            QueryCargoZoneByIdRequest zoneByIdRequest = new QueryCargoZoneByIdRequest();
            List<String> cargoZoneIds = new ArrayList<>();
            cargoZoneIds.add(orderSDO.getWareHouseCode());
            zoneByIdRequest.setCargoZoneIdList(cargoZoneIds);
            QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = doHandler$callAPI3(zoneByIdRequest);
            JSONArray cargoJsonArray = JSONObject.parseObject(JSONObject.toJSONString(queryCargoZoneByIdResponse)).getJSONArray("result");
            if (CollectionUtils.isNotEmpty(cargoJsonArray)) {
                sdo.setDeliveryFactoryCode(cargoJsonArray.getJSONObject(0).getString("sapFactoryCode"));
                sdo.setDeliveryInventoryCode(cargoJsonArray.getJSONObject(0).getString("warehouseCode"));
            }

            //平台渠道->sap
            BaselineQueryChannelByPageRequest channelByPageRequest = new BaselineQueryChannelByPageRequest();
            channelByPageRequest.setChannelCode(orderSDO.getChannelCode());
            Map map = (Map) baseDataService.baselineQueryChannelByPage(channelByPageRequest);
            JSONObject jsonMap = JSONObject.parseObject(JSONObject.toJSONString(map));
            JSONArray jsonArray = jsonMap.getJSONObject("result").getJSONArray("content");
            if (CollectionUtils.isNotEmpty(jsonArray)) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                sdo.setSapChannel(jsonObject1.getString("outCode"));
            }
            //todo 平台货品组->sap
            /*QueryScItemGroupRequest scItemGroupRequest = new QueryScItemGroupRequest();
            List<String> idList = new ArrayList<>();
            idList.add(orderSDO.getProductGroupCode());
            scItemGroupRequest.setIdList(idList);
            PageQueryScItemGroupListResponse scItemGroupListResponse = doHandler$queryScItemGroup(scItemGroupRequest);
            if (CollectionUtils.isNotEmpty(scItemGroupListResponse.getResult())) {
                JSONArray scItemGroups = JSONObject.parseArray(JSONObject.toJSONString(scItemGroupListResponse.getResult()));
                sdo.setProductGroupCode(scItemGroups.getJSONObject(0).getString("code"));
            }*/
            sdo.setProductGroupCode(orderSDO.getProductGroupCode());
            sdo.setCreator(orderSDO.getCreatorName());
            if (orderSDO.getGmtCreate() != null) {
                sdo.setCreateTime(DateFormatUtils.format(orderSDO.getGmtCreate(), "yyyy-MM-dd HH:mm:ss"));
                sdo.setDocTime(DateFormatUtils.format(orderSDO.getGmtCreate(), "yyyy-MM-dd"));
            }
            sdo.setSoldPartCode(orderSDO.getCustomerCode());
            sdo.setDeliveryPartCode(orderSDO.getReceiveAddressCode());
            sdo.setDeliveryPartName(orderSDO.getReceiveDetailAddress());
            if (orderSDO.getCustomerExpectDate() != null) {
                sdo.setExpectedDeliveryTime(DateFormatUtils.format(orderSDO.getCustomerExpectDate(),"yyyy-MM-dd"));
            }
            sdo.setShipType(orderSDO.getTransportModeCode());
            sdo.setCashCustomerName(orderSDO.getCashCustomerName());
            sdo.setCostCenter(orderSDO.getCostCenter());
            sdo.setOrderReason(orderSDO.getCreateReason());
            //sdo.setFeatures(orderSDO.getFeatureStr());
            sdo.setPurchaseNo(orderSDO.getCustomerReferenceNumber());
            sdo.setPurchaseDate(orderSDO.getCustomerExpectDate() == null ? null: DateFormatUtils.format(orderSDO.getCustomerExpectDate(),"yyyy-MM-dd"));
            sdo.setRemark(orderSDO.getRemark());
            sdo.setTradeOrderLineId(orderLineSDO.getSerialNumber());

            //平台货品->sap
            BaselineQueryScItemByPageRequest scItemByPageRequest = new BaselineQueryScItemByPageRequest();
            List<String> ids = new ArrayList<>();
            ids.add(orderLineSDO.getScItemSDO().getScItemId());
            scItemByPageRequest.setIdList(ids);
            Map scItemMap = doHandler$callAPI2(scItemByPageRequest);
            JSONArray scItemArray = JSONObject.parseObject(JSONObject.toJSONString(scItemMap)).getJSONObject("result").getJSONObject("result").getJSONArray("searchResult");
            if (CollectionUtils.isNotEmpty(scItemArray)) {
                sdo.setScItemId(scItemArray.getJSONObject(0).getString("outerId"));
            }
            sdo.setQuantity(orderLineSDO.getScItemSDO().getQuantity().toString());
            //todo  销售单位先硬编码 之后再改
            sdo.setSaleUnit(orderLineSDO.getScItemSDO().getSaleUnit());
            sdo.setBaseUint(orderLineSDO.getScItemSDO().getInventoryUnitCode());
            sdo.setReturnFlag(orderLineSDO.getReturnCharacter());

            Long unitPrice = orderLineSDO.getScItemSDO().getUnitPrice();
            if (unitPrice != null) {
                sdo.setPrice(PriceConvertUnit.convertToYuan(unitPrice.toString()));
            }

            //现金订单和退货订单  price字段给手工总金额
            if (StringUtils.isNotBlank(orderSDO.getOrderType())) {
                if (SaleOrderTag.CASH_ORDER.getCode().equals(orderSDO.getOrderType()) || SaleOrderTag.STD_RETURN_ORDER.getCode().equals(orderSDO.getOrderType())) {
                    if (MapUtils.isNotEmpty(orderLineSDO.getFeatures()) && StringUtils.isNotBlank(orderLineSDO.getFeatures().get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT))) {
                        sdo.setPrice(PriceConvertUnit.convertToYuan(orderLineSDO.getFeatures().get(SaleOrderConstants.MANUAL_TOTAL_AMOUNT)));
                    }
                }
            }

            Long activityPrice = orderLineSDO.getScItemSDO().getActivityPrice();
            if (activityPrice != null ) {
                sdo.setActivityPrice(PriceConvertUnit.convertToYuan(activityPrice.toString()));
            }

            sdo.setRemark(orderLineSDO.getRemark());
            sdo.setCostCenter(orderSDO.getCostCenter());
            sdo.setOrderReason(orderSDO.getCreateReason());
//            if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
//                sdo.setFeatures(JSONObject.toJSONString(orderLineSDO.getFeatures()));
//            }

            if (MapUtils.isNotEmpty(orderLineSDO.getFeatures())) {
                sdo.setExt(orderLineSDO.getFeatures().get("giftsMainSingle"));
            }

            if ("return".equals(orderLineSDO.getOrderLineTag()) && orderSDO.getOrderType().equals(SaleOrderTag.EXCHANGE_ORDER.getCode())) {
                sdo.setReturnFlag("1");
            }

            //add by 皓晖 at 20211217 for 014接口使用预留字段ext2下发我们订单抬头备注字段begin
            sdo.setExt2(orderSDO.getRemark());
            //add by 皓晖 at 20211217 for 014接口使用预留字段ext2下发我们订单抬头备注字段end

            return sdo;
        }).collect(Collectors.toList());

        request.setData(mnSapIf014DetailList);
        log.info("订单同步sap入参： request = {} " , request);
        return doHandler$callAPI(request);
    }

    /**
     * 价格转换 ,这里临时使用 10000，为了是把数据推送下去。
     * @param price
     * @return
     */
    private String priceConvert(String price) {
        BigDecimal tmpValue = new BigDecimal(price);
        String tmpPrice = tmpValue.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_DOWN).toString();
        return tmpPrice;
    }
}
